/**
 * 设备检测工具函数
 */

export interface DeviceInfo {
  type: 'mobile' | 'pc' | 'tablet'
  width: number
  height: number
  userAgent: string
  isTouch: boolean
  platform: string
}

export interface DeviceDetectionResult {
  targetPage: string
  deviceType: string
  confidence: number
}

/**
 * 获取设备信息
 */
export const getDeviceInfo = (): DeviceInfo => {
  const width = typeof window !== 'undefined' ? window.innerWidth : 0
  const height = typeof window !== 'undefined' ? window.innerHeight : 0
  const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : ''
  const platform = typeof navigator !== 'undefined' ? navigator.platform : ''
  
  // 检测是否为触摸设备
  const isTouch = 'ontouchstart' in window || 
                  navigator.maxTouchPoints > 0 || 
                  /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)
  
  return {
    width,
    height,
    userAgent,
    isTouch,
    platform
  }
}

/**
 * 智能设备检测
 */
export const detectDevice = (): DeviceDetectionResult => {
  const deviceInfo = getDeviceInfo()
  const { width, userAgent, isTouch } = deviceInfo
  
  let type: 'mobile' | 'pc' | 'tablet' = 'pc'
  let confidence = 0.5
  
  // 基于屏幕宽度的检测
  if (width < 768) {
    type = 'mobile'
    confidence += 0.3
  } else if (width < 1024) {
    type = 'tablet'
    confidence += 0.2
  } else {
    type = 'pc'
    confidence += 0.3
  }
  
  // 基于User Agent的检测
  const mobileRegex = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i
  const tabletRegex = /iPad|Android(?=.*\bMobile\b)(?=.*\bSafari\b)/
  
  if (mobileRegex.test(userAgent)) {
    if (tabletRegex.test(userAgent)) {
      type = 'tablet'
      confidence += 0.4
    } else {
      type = 'mobile'
      confidence += 0.4
    }
  }
  
  // 基于触摸能力的检测
  if (isTouch && type === 'pc') {
    type = 'tablet'
    confidence += 0.2
  }
  
  // 确定目标页面
  let targetPage = ''
  let deviceType = ''
  
  switch (type) {
    case 'mobile':
      targetPage = '/pages/index/index'
      deviceType = '移动端'
      break
    case 'tablet':
      // 平板可以选择移动端或PC端，这里默认选择PC端以获得更好的体验
      targetPage = '/pages/index/pcindex'
      deviceType = '平板端'
      break
    case 'pc':
      targetPage = '/pages/index/pcindex'
      deviceType = 'PC端'
      break
  }
  
  return {
    targetPage,
    deviceType,
    confidence: Math.min(confidence, 1)
  }
}

/**
 * 获取用户偏好
 */
export const getUserPreference = (): string | null => {
  try {
    return Taro.getStorageSync('userDevicePreference')
  } catch (error) {
    console.warn('获取用户偏好失败:', error)
    return null
  }
}

/**
 * 保存用户偏好
 */
export const saveUserPreference = (preference: 'mobile' | 'pc'): void => {
  try {
    Taro.setStorageSync('userDevicePreference', preference)
  } catch (error) {
    console.warn('保存用户偏好失败:', error)
  }
}

/**
 * 清除用户偏好
 */
export const clearUserPreference = (): void => {
  try {
    Taro.removeStorageSync('userDevicePreference')
  } catch (error) {
    console.warn('清除用户偏好失败:', error)
  }
}
